import sqlite3
from pathlib import Path


class DatabaseManager:
    def __init__(self, db_filename="fenbi.db"):
        documents_path = Path.home() / "Documents" / "fenbi_crawler"
        self.db_path = documents_path / db_filename
        documents_path.mkdir(parents=True, exist_ok=True) # 没有文件则创建
        self.conn = sqlite3.connect(self.db_path)
        self.conn.row_factory = sqlite3.Row  # 支持字典风格
        self.cursor = self.conn.cursor()

    def __enter__(self):
        return self

    # 自动关闭资源
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

    # 执行不返回结果的sql（insert、update、delete）
    def execute(self, sql, params=()):
        with self.conn:
            self.cursor.execute(sql, params)

    # 查询所有
    def fetch_all(self, sql, params=()):
        self.cursor.execute(sql, params)
        return [dict(row) for row in self.cursor.fetchall()]

    # 查询一条
    def fetch_one(self, sql, params=()):
        self.cursor.execute(sql, params)
        row = self.cursor.fetchone()
        return dict(row) if row else None

    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.conn:
            self.conn.close()
